package api

import (
	"smoot-code/service/data"
	"smoot-code/service/types"
	"sync"
)

type EditorApi struct {
	data data.Data
}

var Editor *EditorApi
var onceEditor sync.Once

func (s *EditorApi) GetTemplateFiles(dir string, key string) types.Resp {
	files, err := s.data.GetTemplateFiles(dir, key)
	success := true
	msg := "Success"
	if err != nil {
		success = false
		msg = err.Error()
	}
	resMap := make(map[string]types.FileInfo)
	for _, file := range files {
		resMap[file.Path] = file
	}

	return types.Resp{
		Success: success,
		Data:    resMap,
		Msg:     msg,
	}
}
func (s *EditorApi) GetConfigFiles(key string) types.Resp {
	files, err := s.data.GetConfigFiles(key)
	success := true
	msg := "Success"
	if err != nil {
		success = false
		msg = err.Error()
	}
	resMap := make(map[string]types.FileInfo)
	for _, file := range files {
		resMap[file.Path] = file
	}

	return types.Resp{
		Success: success,
		Data:    resMap,
		Msg:     msg,
	}
}

func (s *EditorApi) GetVarFiles(key string) types.Resp {
	files, err := s.data.GetVarFiles(key)
	success := true
	msg := "Success"
	if err != nil {
		success = false
		msg = err.Error()
	}
	resMap := make(map[string]types.FileInfo)
	for _, file := range files {
		resMap[file.Path] = file
	}

	return types.Resp{
		Success: success,
		Data:    resMap,
		Msg:     msg,
	}
}

func (s *EditorApi) EditFile(path string, content string) types.Resp {
	err := s.data.EditFile(path, content)
	success := true
	msg := "Success"
	if err != nil {
		success = false
		msg = err.Error()
	}

	return types.Resp{
		Success: success,
		Msg:     msg,
	}
}
func (s *EditorApi) RenameFile(name string, newName string) types.Resp {
	err := s.data.RenameFile(name, newName)
	success := true
	msg := "Success"
	if err != nil {
		success = false
		msg = err.Error()
	}

	return types.Resp{
		Success: success,
		Msg:     msg,
	}
}

func (s *EditorApi) NewFile(name string, isDir bool) types.Resp {
	err := s.data.NewFile(name, isDir)
	success := true
	msg := "Success"
	if err != nil {
		success = false
		msg = err.Error()
	}

	return types.Resp{
		Success: success,
		Msg:     msg,
	}
}

func (s *EditorApi) DeleteFile(name string) types.Resp {
	err := s.data.DeleteFile(name)
	success := true
	msg := "Success"
	if err != nil {
		success = false
		msg = err.Error()
	}

	return types.Resp{
		Success: success,
		Msg:     msg,
	}
}
func NewEditor(datas data.Data) *EditorApi {
	if Editor == nil {
		onceEditor.Do(func() {
			Editor = &EditorApi{datas}

		})
	}
	return Editor
}
